package com.shangxia.lucky.lucky.job.write;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.shangxia.lucky.lucky.ConfigText;
import com.shangxia.lucky.lucky.common.FactoryHead;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.time.DateFormatUtils;

import java.util.Date;
import java.util.LinkedList;
import java.util.List;


/**
 * @ProjectName: monomer
 * @ClassName: OverWriterThread
 * @Time: 2021/9/4
 * @Author: zhouy
 * @Description:
 * @Experience:
 */

@Slf4j
@Data
@NoArgsConstructor
public class MatchGroupWriterThread implements Runnable, ExportThreadJobOver {

    public volatile static boolean WRITER_OVER_LOG = false;
    public volatile Boolean MATCH_GROUP_WRITE_FLAG = false;
    public final static LinkedList<List<List<String>>> groupQueue = new LinkedList<>();

    public ConfigText configText;

    public MatchGroupWriterThread(ConfigText configText) {
        this.configText = configText;
    }


    @Override
    public void run() {
        String batchFile = configText.getBananaAbsoluteResultPath() + DateFormatUtils.format(new Date(), "yyyy-MM-dd_H-mm-ss_分批") + ".xlsx";
        ExcelWriter excelWriter = EasyExcel.write(batchFile).build();
        WriteSheet ageSheet = EasyExcel.writerSheet("分批")
                .head(FactoryHead.groupHead()).build();
        log.info("结果输出 开始");
        while (!over() || !groupQueue.isEmpty()) {
            List<List<String>> groupLists = groupQueue.poll();
            if (null != groupLists) {
                excelWriter.write(groupLists, ageSheet);
            }
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        excelWriter.finish();
        WRITER_OVER_LOG = true;
        log.info("结果输出结束");
    }

    public void stop() {
        this.setMATCH_GROUP_WRITE_FLAG(false);
    }

    @Override
    public Boolean over() {
        return MATCH_GROUP_WRITE_FLAG;
    }
}
